package chan.project.smartlawdatamanage.controller.inner;

import chan.project.smartlawcommon.annotation.AuthCheck;
import chan.project.smartlawcommon.common.ErrorCode;
import chan.project.smartlawcommon.exception.BusinessException;
import chan.project.smartlawdatamanage.service.LawRegulationService;
import chan.project.smartlawmodel.entity.Instrument;
import chan.project.smartlawmodel.entity.LawRegulation;
import chan.project.smartlawservice.dataManage.DataManageFeignClient;
import cn.hutool.core.collection.CollectionUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/data/inner")
public class DataInnerController implements DataManageFeignClient {

    @Resource
    private LawRegulationService lawRegulationService;

    @Resource
    private ElasticsearchClient elasticsearchClient;


    /**
     * 获取所有法律法规名称
     * @return
     */
    @Override
    @AuthCheck(mustRole = "data_admin")
    @GetMapping("/getLaw")
    public List<String> getAllLawFileName(){
        List<String> list = new ArrayList<>();
        List<LawRegulation> lawRegulations = lawRegulationService.list();
        if(CollectionUtil.isEmpty(lawRegulations)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"数据库还未存储法律法规");
        }
        for (LawRegulation lawRegulation : lawRegulations) {
            list.add(lawRegulation.getTitle());
        }
        return list;
    }

    /**
     * 获取最新版本的法律法规
     * @param title
     * @return
     */
    @Override
    @AuthCheck(mustRole = "data_admin")
    @GetMapping("/getLastLaw")
    public LawRegulation getLastLaw(@RequestParam("title") String title) {
        LambdaQueryWrapper<LawRegulation> lawRegulationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        lawRegulationLambdaQueryWrapper.eq(LawRegulation::getTitle,title);
        lawRegulationLambdaQueryWrapper.orderByDesc(LawRegulation::getVersion);
        lawRegulationLambdaQueryWrapper.last("LIMIT 1");
        LawRegulation one = lawRegulationService.getOne(lawRegulationLambdaQueryWrapper);
        return one;
    }

    /**
     * 根据关键词列表查询案件
     * @param keywords
     * @return
     */
    @GetMapping("/get/legal")
    @Override
    public List<Instrument> getLegalCase(@RequestParam("keywords") List<String> keywords) {
        if (keywords == null || keywords.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "关键词列表为空");
        }
        try {
            // 构建搜索请求
            SearchRequest searchRequest = SearchRequest.of(s -> s
                    .index("instrument_index") // 索引名称
                    .query(q -> q
                    .bool(b -> {
                            BoolQuery.Builder boolBuilder = b;
                            // 遍历所有关键词，添加到 should 子句中
                            for (String keyword : keywords) {
                                boolBuilder.should(sh -> sh
                                                .match(m -> m
                                                    .field("caseReason")
                                                    .query(keyword)
                                                    .boost(2.0f)))
                                        .should(sh -> sh
                                                .match(m -> m
                                                    .field("title")
                                                    .query(keyword)
                                                    .boost(2.0f)))
                                        .should(sh -> sh
                                                .match(m -> m
                                                    .field("content")
                                                    .query(keyword)))
                                        .should(sh -> sh
                                                .match(m -> m
                                                    .field("court")
                                                    .query(keyword)));
                            }
                            // 至少有一个 should 条件匹配
                            return boolBuilder.minimumShouldMatch("1");
                        })
                    )
                    .source(src -> src
                        .filter(f -> f
                            .includes(Arrays.asList(
                                "caseReason", "caseNumber", "judgmentDate", "title", "content", "court"
                            ))
                        )
                    )
                    .from(0)
                    .size(10)
                    .sort(so -> so
                        .field(f -> f
                            .field("judgmentDate")
                            .order(SortOrder.Desc)))
            );

            // 执行搜索
            SearchResponse<Instrument> searchResponse = elasticsearchClient.search(
                    searchRequest,
                    Instrument.class // 映射到 Instrument 类
            );

            // 解析结果
            List<Hit<Instrument>> hits = searchResponse.hits().hits();
            List<Instrument> instruments = new ArrayList<>();

            for (Hit<Instrument> hit : hits) {
                Instrument instrument = hit.source();
                if (instrument != null) {
                    instruments.add(instrument);
                }
            }
            return instruments;
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "搜索失败: " + e.getMessage());
        }
    }
}
